<template>
  <div class="statistics-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <!-- 返回上一页 -->
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
    </div>

    <!-- 基本统计卡片 -->
    <div class="stats-cards">
      <StatCard title="衣物总数" :value="clothesCount" icon="👕" />
      <StatCard title="收藏数量" :value="favoriteCount" icon="❤️" />
      <StatCard title="穿搭次数" :value="wearCount" icon="👟" />
      <StatCard title="本月新增" :value="monthlyAdded" icon="📈" />
    </div>

    <!-- 分类统计图表 -->
    <div class="chart-section">
      <div class="section-title">分类分布</div>
      <div class="chart-container">
        <canvas ref="categoryChart"></canvas>
      </div>
    </div>

    <!-- 季节统计图表 -->
    <div class="chart-section">
      <div class="section-title">季节分布</div>
      <div class="chart-container">
        <canvas ref="seasonChart"></canvas>
      </div>
    </div>

    <!-- 颜色统计图表 -->
    <div class="chart-section">
      <div class="section-title">颜色分布</div>
      <div class="chart-container">
        <canvas ref="colorChart"></canvas>
      </div>
    </div>

    <!-- 穿着频率分析 -->
    <div class="chart-section">
      <div class="section-title">穿着频率最高的衣物</div>
      <div class="wear-frequency-list">
        <div
          v-for="(item, index) in topWearFrequency"
          :key="item.id"
          class="wear-frequency-item"
        >
          <div class="rank">{{ index + 1 }}</div>
          <div class="item-image">
            <img
              :src="
                item.imageUrls?.[0] ||
                'https://gd-hbimg.huaban.com/f5773e512a1d749bce5dfd456ac8958c23d1148edf16-z6vbGy_fw658webp'
              "
              :alt="item.name"
            />
          </div>
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-category">
              {{ item.type[0].text }} > {{ item.type[1].text }}
            </div>
          </div>
          <div class="wear-count">
            <div class="count">{{ item.wearCount || 0 }}次</div>
          </div>
        </div>

        <div v-if="topWearFrequency.length === 0" class="empty-frequency">
          <p>暂无穿着数据</p>
        </div>
      </div>
    </div>

    <!-- 衣橱建议 -->
    <div class="suggestion-section">
      <div class="section-title">衣橱建议</div>
      <div class="suggestion-content">
        <ul>
          <li v-for="suggestion in wardrobeSuggestions" :key="suggestion.id">
            {{ suggestion.text }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useClothesStore } from "../store/clothes";
import StatCard from "../components/StatCard.vue";

// 初始化路由
const router = useRouter();

// 导入Chart.js
let Chart = null;
let categoryChartInstance = null;
let seasonChartInstance = null;
let colorChartInstance = null;

// 组件挂载后导入Chart.js
onMounted(() => {
  import("chart.js/auto").then((module) => {
    Chart = module.Chart;
    initCharts();
  });
});

const clothesStore = useClothesStore();
const categoryChart = ref(null);
const seasonChart = ref(null);
const colorChart = ref(null);

// 返回上一页
const goBack = () => {
  router.back();
};

// 计算属性
const clothesCount = computed(() => clothesStore.clothesList.length);
const favoriteCount = computed(
  () => clothesStore.clothesList.filter((item) => item.isFavorite).length
);
const wearCount = computed(() =>
  clothesStore.clothesList.reduce(
    (total, item) => total + (item.wearCount || 0),
    0
  )
);
const monthlyAdded = computed(() => {
  const now = new Date();
  const currentMonth = now.getMonth();
  const currentYear = now.getFullYear();

  return clothesStore.clothesList.filter((item) => {
    if (!item.createdAt) return false;
    const itemDate = new Date(item.createdAt);
    return (
      itemDate.getMonth() === currentMonth &&
      itemDate.getFullYear() === currentYear
    );
  }).length;
});

// 穿着频率最高的衣物（前5名）
const topWearFrequency = computed(() => {
  console.log(clothesStore.clothesList);

  return [...clothesStore.clothesList]
    .sort((a, b) => (b.wearCount || 0) - (a.wearCount || 0))
    .slice(0, 5);
});

// 衣橱建议
const wardrobeSuggestions = computed(() => {
  const suggestions = [];

  // 基于衣物数量的建议
  if (clothesCount.value === 0) {
    suggestions.push({
      id: 1,
      text: "您的衣橱还是空的，开始添加您的第一件衣物吧！",
    });
  } else if (clothesCount.value < 10) {
    suggestions.push({
      id: 2,
      text: "您的衣橱比较精简，可以考虑添加一些不同风格的衣物以增加搭配可能性。",
    });
  }

  // 基于季节分布的建议
  const seasonStats = clothesStore.seasonStats;
  const total = Object.values(seasonStats).reduce(
    (sum, count) => sum + count,
    0
  );
  if (total > 0) {
    Object.entries(seasonStats).forEach(([season, count]) => {
      const percentage = (count / total) * 100;
      if (percentage < 10) {
        suggestions.push({
          id: 3,
          text: `${season}的衣物较少，考虑添加一些适合${season}的衣物。`,
        });
      }
    });
  }

  // 基于分类分布的建议
  const categoryStats = clothesStore.categoryStats;
  if (categoryStats) {
    // 可以根据分类分布给出建议
  }

  // 基于收藏的建议
  if (
    favoriteCount.value > 0 &&
    favoriteCount.value < clothesCount.value * 0.3
  ) {
    suggestions.push({
      id: 4,
      text: "您收藏的衣物不多，可以将喜欢的衣物标记为收藏，方便快速查找。",
    });
  }

  // 默认建议
  if (suggestions.length === 0) {
    suggestions.push({ id: 5, text: "您的衣橱搭配很合理，继续保持！" });
  }

  return suggestions;
});

// 初始化图表
const initCharts = () => {
  // 分类统计图表
  if (categoryChart.value && Chart) {
    const categoryStats = clothesStore.categoryStats;

    const labels = Object.keys(categoryStats);
    const data = Object.values(categoryStats);

    const colors = generateColors(labels.length);

    if (categoryChartInstance) {
      categoryChartInstance.destroy();
    }

    categoryChartInstance = new Chart(categoryChart.value, {
      type: "pie",
      data: {
        labels: labels,
        datasets: [
          {
            data: data,
            backgroundColor: colors,
            borderWidth: 2,
            borderColor: "#fff",
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: "right",
          },
          title: {
            display: true,
            text: "各分类衣物数量",
          },
        },
      },
    });
  }

  // 季节统计图表
  if (seasonChart.value && Chart) {
    const seasonStats = clothesStore.seasonStats;
    const labels = Object.keys(seasonStats);
    const data = Object.values(seasonStats);

    const colors = ["#95ec69", "#ff7875", "#ffa940", "#4dabf7"];

    if (seasonChartInstance) {
      seasonChartInstance.destroy();
    }

    seasonChartInstance = new Chart(seasonChart.value, {
      type: "bar",
      data: {
        labels: labels,
        datasets: [
          {
            label: "衣物数量",
            data: data,
            backgroundColor: colors,
            borderWidth: 0,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          title: {
            display: true,
            text: "各季节衣物分布",
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              stepSize: 1,
            },
          },
        },
      },
    });
  }

  // 颜色统计图表
  if (colorChart.value && Chart) {
    // 计算颜色统计
    const colorStats = {};
    clothesStore.clothesList.forEach((clothes) => {
      if (!colorStats[clothes.color]) {
        colorStats[clothes.color] = 0;
      }
      colorStats[clothes.color]++;
    });
    const labels = Object.keys(colorStats);
    const data = Object.values(colorStats);

    const colorValues = {
      红色: "#ff4d4f",
      橙色: "#fa8c16",
      黄色: "#fadb14",
      绿色: "#52c41a",
      蓝色: "#1890ff",
      紫色: "#722ed1",
      黑色: "#000000",
      白色: "#ffffff",
      灰色: "#8c8c8c",
      花色: "#87ceeb",
    };

    const bgColors = labels.map((label) => colorValues[label] || "#cccccc");

    if (colorChartInstance) {
      colorChartInstance.destroy();
    }

    colorChartInstance = new Chart(colorChart.value, {
      type: "doughnut",
      data: {
        labels: labels,
        datasets: [
          {
            data: data,
            backgroundColor: bgColors,
            borderWidth: 2,
            borderColor: "#fff",
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: "right",
          },
          title: {
            display: true,
            text: "衣物颜色分布",
          },
        },
      },
    });
  }
};

// 生成随机颜色
const generateColors = (count) => {
  const colors = [];
  const baseColors = ["#409eff", "#f56c6c", "#67c23a", "#e6a23c", "#909399"];

  for (let i = 0; i < count; i++) {
    if (i < baseColors.length) {
      colors.push(baseColors[i]);
    } else {
      // 生成随机颜色
      const r = Math.floor(Math.random() * 255);
      const g = Math.floor(Math.random() * 255);
      const b = Math.floor(Math.random() * 255);
      colors.push(`rgb(${r}, ${g}, ${b})`);
    }
  }

  return colors;
};

// 加载衣物数据
const loadClothes = async () => {
  try {
    await clothesStore.fetchClothesList();
    // 数据加载后初始化图表
    if (Chart) {
      initCharts();
    }
  } catch (error) {
    console.error("加载衣物数据失败:", error);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadClothes();
});

// 组件卸载时销毁图表实例
onUnmounted(() => {
  if (categoryChartInstance) {
    categoryChartInstance.destroy();
  }
  if (seasonChartInstance) {
    seasonChartInstance.destroy();
  }
  if (colorChartInstance) {
    colorChartInstance.destroy();
  }
});
</script>

<style scoped>
.statistics-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  /* padding: 14px 16px; */

  font-size: 20px;
  color: #333;
  margin: 0 0 20px 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  position: relative;
}

.wear-frequency-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.wear-frequency-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.rank {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: white;
  font-weight: bold;
  border-radius: 50%;
  margin-right: 15px;
  font-size: 14px;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.item-category {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.wear-count {
  text-align: right;
}

.count {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.percentage {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.empty-frequency {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.suggestion-content {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
}

.suggestion-content ul {
  margin: 0;
  padding-left: 20px;
}

.suggestion-content li {
  color: #666;
  line-height: 1.8;
  margin-bottom: 8px;
}

.suggestion-content li:last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .statistics-container {
    padding: 15px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .chart-container {
    height: 250px;
  }

  .wear-frequency-item {
    flex-wrap: wrap;
  }

  .wear-count {
    margin-top: 10px;
    width: 100%;
    text-align: left;
  }
}
</style>
